package com.fas.core.plugin.shiro.realm;

import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.fas.hehe.system.model.LoginUser;
import com.fas.hehe.system.model.User;
import com.fas.hehe.system.service.UserService;
/**
 * 
 * 基础REALM
 *
 * @Copyright: Copyright (c) 2016 FAS 
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月24日 下午10:13:56
 * @version V1.0
 */
public abstract class BaseRealm extends AuthorizingRealm {

    protected UserService userService;

    public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}
	
	protected LoginUser createLoginUser(User user,LoginUser.LoginBy loginBy){
        //将登录用户保存Session
        LoginUser loginUser = new LoginUser();
        loginUser.setUserName(user.getUsername());
        loginUser.setCompanyId(user.getCompanyId());
        loginUser.setDepartmentId(user.getDepartmentId());
        loginUser.setEmail(user.getEmail());
        loginUser.setMobile(user.getMobile());
        loginUser.setLoginBy(loginBy);
        loginUser.setUserId(user.getId());
        loginUser.setUserNameZh(user.getUsernameZh());
        //loginUser.setSuperUser(superUser);
        //loginUser.setLoginDeviceType(userAgent.getOperatingSystem().getDeviceType());
        // TODO  
        return loginUser;
	}
	
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		LoginUser loginUser = (LoginUser)principals.getPrimaryPrincipal();
		Long userId  = loginUser.getUserId();
        userService = new UserService();
        
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRolesStr(userId));
        authorizationInfo.setStringPermissions(userService.findPermissions(userId));
        return authorizationInfo;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
}

